package com.victor.zjbj_android.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.victor.zjbj_android.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shuttle on 2017/12/16.
 */

public class PhotoPopupManager {
    private static final String TAG = PhotoPopupManager.class.getSimpleName();
    private volatile static PhotoPopupManager sInstance;

    private Activity mActivity;
    private PopupWindow mPopup;
    private static final String IMAGE_TYPE = "image/*";

    private static final int REQUEST_GALLERY = 0x666;
    private static final int REQUEST_CAMERA = 0x777;

    private String photoPath;

    private List<OnPhotoSelectedListener> listenerArray = new ArrayList<>();

    private PhotoPopupManager() {
    }

    /**
     * Singleton
     *
     * @return
     */
    public static PhotoPopupManager getInstance() {
        if (sInstance == null) {
            synchronized (PhotoPopupManager.class) {
                if (sInstance == null) {
                    sInstance = new PhotoPopupManager();
                }
            }
        }
        return sInstance;
    }

    /**
     * 显示
     *
     * @param activity
     */
    public void show(Activity activity) {
        if (!checkActivityLeak(activity)) {
            return;
        }
        initPopup();
    }

    /**
     * 是否可见
     *
     * @return
     */
    public boolean isVisible() {
        if (mPopup != null) {
            return mPopup.isShowing();
        }
        return false;
    }

    /**
     * 隐藏
     */
    public void dismiss() {
        if (mPopup != null) {
            mPopup.dismiss();
        }
    }

    private void initPopup() {
        View rootView = LayoutInflater.from(mActivity).inflate(R.layout.layout_photo_popup, null);
        mPopup = new PopupWindow(rootView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopup.setOutsideTouchable(true);
        mPopup.setAnimationStyle(R.style.MyPopupWindow_anim_style);
        mPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroudAlpha(1.0f);
            }
        });
        TextView tvGallery = rootView.findViewById(R.id.tv_gallery);
        TextView tvCamera = rootView.findViewById(R.id.tv_camera);
        TextView tvCancel = rootView.findViewById(R.id.tv_cancel);
        mPopup.showAtLocation(tvCancel, Gravity.BOTTOM, 0, 0);
        setBackgroudAlpha(0.4f);
        RelativeLayout rlRoot = rootView.findViewById(R.id.rl_root);
        rlRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopup != null && mPopup.isShowing()) {
                    mPopup.dismiss();
                }
            }
        });

        // camera
        tvCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopup != null && mPopup.isShowing()) {
                    mPopup.dismiss();
                }
                gotoCamera();
            }
        });
        // gallery
        tvGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopup != null && mPopup.isShowing()) {
                    mPopup.dismiss();
                }
                gotoGallery();
            }
        });
        // 取消
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopup != null && mPopup.isShowing()) {
                    mPopup.dismiss();
                }
                for (OnPhotoSelectedListener listener : listenerArray) {
                    if (listener != null) {
                        listener.onPhotoSelected("");
                    }
                }
            }
        });
    }

    /**
     * 前往相册
     */
    private void gotoGallery() {
        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0x32);
        } else {
            Intent intent = new Intent();
            intent.setType(IMAGE_TYPE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            mActivity.startActivityForResult(intent, REQUEST_GALLERY);
        }
    }

    /**
     * 前往相机
     */
    @SuppressLint("SimpleDateFormat")
    private void gotoCamera() {
        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 0x31);
        } else {
            Intent intent = null;
            //file
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            File file = PhotoUtils.getCacheFilePath(mActivity, sdf.format(System.currentTimeMillis()));
            photoPath = file.getAbsolutePath();

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                mActivity.startActivityForResult(intent, REQUEST_CAMERA);
                Log.e("camera","11");
            } else {
                try {
                    Log.e("camera","22");
                    intent = new Intent();
                    Uri uri = FileProvider.getUriForFile(mActivity, "com.victor.zjbj_android.fileprovider", file);
                    //对目标应用临时授权该URI所代表的文件
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    //设置Action为拍照
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    mActivity.startActivityForResult(intent, REQUEST_CAMERA);
                } catch (SecurityException e) {
                    e.printStackTrace();
                    intent = new Intent();
                    intent.setAction(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                    mActivity.startActivity(intent);
                }
            }
        }
    }

    /**
     * 在宿主Activity回调，获取从相册或者相机传回来的值
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResulted(Activity activity, int requestCode, int resultCode, Intent data) {
        if (!checkActivityLeak(activity)) {
            mActivity = activity;
        }
        switch (requestCode) {
            case REQUEST_CAMERA:
                if (resultCode != Activity.RESULT_OK) {
                    photoPath = "";
                }
                break;
            case REQUEST_GALLERY:
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = data.getData();
                    photoPath = PhotoUtils.getPath(mActivity, uri);
                } else {
                    photoPath = "";
                }
                break;
            default:
                break;
        }
        for (OnPhotoSelectedListener listener : listenerArray) {
            if (listener != null) {
                listener.onPhotoSelected(photoPath);
                Log.e(TAG, "===> path = " + photoPath);
            }
        }
        // 全局变量可能导致数据一直存在
        photoPath = "";
    }

    /**
     * 半透明背景
     *
     * @param alpha
     */
    private void setBackgroudAlpha(float alpha) {
        Window window = mActivity.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = alpha;
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        window.setAttributes(lp);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private boolean checkActivityLeak(Activity activity) {
        if (activity != null) {
            if (activity.isFinishing() || activity.isDestroyed()) {
                return false;
            }
        } else {
            return false;
        }
        mActivity = activity;
        return true;
    }

    public interface OnPhotoSelectedListener {
        void onPhotoSelected(String photoPath);
    }

    public void setOnPhotoSelectedListener(OnPhotoSelectedListener listener) {
        if (listener != null) {
            listenerArray.add(listener);
        }
    }
}
